<script setup>
import {
  Edit,
  Delete,
  Close
} from '@element-plus/icons-vue'


import {ref} from 'vue'


const addPlates = ref([

])

const queryPlates = ref([

])

const userInfos = ref([

])
const queryTime = ref([])

const resourceTypes = ref([
  {
    "id": 0,
    "resourceValue": "文字",
  },
  {
    "id": 1,
    "resourceValue": "图片",
  }
  ,
  {
    "id": 3,
    "resourceValue": "文字+图片",
  }
  ,
  {
    "id": 4,
    "resourceValue": "文章",
  }
])

const showStates = ref([
  {
    "id": 0,
    "resourceValue": "未发布",
  },
  {
    "id": 1,
    "resourceValue": "已发布",
  }
])


const text = ref([])

const article = ref([])

//用户搜索时选中的分类id
const plateId = ref('')

const account = ref('')

const day = ref('')

const name = ref('')


//用户搜索时选中的发布状态
const state = ref('')

const queryState = ref('')

const likeOrder = ref('')

const forwardOrder = ref('')


const interests = ref([])


//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(15)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  intertestList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  intertestList()
}


import {
  interestListRecordListService,
  interestListInterestResourceService,
  interestAddInterestPublishService,
  interestUpdateInterestPublishService,
  interestListPlateService,
  interestDeleteInterestPublishService,
  interestListOfficialAccountService,
  interestPublishInterestPublishService,
  interestTopInterestPublishService,
  interestCancelTopInterestPublishService,
  interestSetPopularService,
  interestCancelPopularService
} from '@/api/interestPublishRecordData.js'


import {Plus} from '@element-plus/icons-vue'
import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const interestModel = ref({

})


//导入token
import {useTokenStore} from '@/stores/token.js';

const tokenStore = useTokenStore();


//上传成功的回调函数
const uploadSuccess = (result) => {
  interestModel.value.imgUrl = result.data;
  console.log(result.data);
}

const uploadAudioSuccess = (result) => {
  interestModel.value.audioUrl = result.data;
  console.log(result.data);
}


//添加文章
import {ElMessage} from 'element-plus'

const addInterestPublish = async (clickState) => {
  //把发布状态赋值给数据模型
  interestModel.value.state = clickState;

  interestModel.value.fileUrl =fileList;
  //调用接口
  let result = await interestAddInterestPublishService(interestModel.value);

  ElMessage.success(result.msg ? result.msg : '添加成功');

  //让抽屉消失
  visibleDrawer.value = false;

  //刷新当前列表
  intertestList()
}

//编辑分类
const updateInterest= async () => {
  interestModel.value.fileUrl =fileList;
  //调用接口
  let result = await interestUpdateInterestPublishService(interestModel.value);

  ElMessage.success(result.msg ? result.msg : '修改成功')

  //调用获取所有分类的函数
  intertestList();

  //隐藏弹窗
  visibleDrawer.value = false;
}


//获取文章列表数据
const intertestList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    account:account.value?account.value:null,
    name:name.value?name.value:null,
    queryState:1,
    plateId: 9,
    likeOrder:likeOrder.value?likeOrder.value:null,
    forwardOrder:forwardOrder.value?forwardOrder.value:null,
    timeFrom: day.value ? day.value : null,
    timeEnd: day.value ? day.value : null,
  }
  let result = await interestListRecordListService(params);

  //渲染视图
  total.value = result.data.total;
  interests.value = result.data.records;

}


intertestList();


const plateList = async () => {
  let addPlatesResult = await interestListPlateService({containsPopular:false,containsFriends:false});
  let queryPlatesResult = await interestListPlateService({containsPopular:false,containsFriends:false});

  //渲染视图

  addPlates.value = addPlatesResult.data;
  queryPlates.value=queryPlatesResult.data;
}


plateList();








const queryUserInfo = async () => {
  let params = {
  }
  let result = await interestListOfficialAccountService(params);

  //渲染视图

  userInfos.value = result.data;

}


queryUserInfo();



const fileList = ref([])


//删除分类
import {ElMessageBox} from 'element-plus'

const deleteInterest = (row) => {
  //提示用户  确认框

  ElMessageBox.confirm(
      '你确认要删除该兴趣圈信息吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //调用接口
        let result = await interestDeleteInterestPublishService(row.id);
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新列表
        intertestList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消了删除',
        })
      })
}


//定义变量,控制标题的展示
const title = ref('')
const showInterest = (row) => {
  visibleDrawer.value = true, title.value = '编辑兴趣圈'
  interestModel.value.plateId = row.plateId;
  interestModel.value.resourceType = row.resourceType;
  interestModel.value.userId = row.userId;
  interestModel.value.title = row.title;
  interestModel.value.text = row.text;
  interestModel.value.article = row.article;
  fileList.value =[];
  for (let i = 0; i < row.images.length; i++) {
    fileList.value.push({
      url:row.images[i].url,
      name:row.images[i].name
    })
  }

  interestModel.value.id = row.id;


}

//清空模型的数据
const clearData = () => {

  interestModel.value.plateId ='';
  interestModel.value.resourceType = '';
  interestModel.value.userId = '';
  interestModel.value.title = '';
  interestModel.value.text = '';
  interestModel.value.article = '';
  interestModel.value.id = '';
  fileList.value =[];
}

const delAudio = () => {
  interestModel.value.audioUrl = '';
}
const delImg = () => {
  interestModel.value.imgUrl = '';
}

const selected = (row, index) => {
  return interests.value[index].publishState == 0
}

let select = []
const publish = async () => {
  console.log(select)
  if (select.length === 0) {
    ElMessage.error("请选择要发布的兴趣圈内容")
    return
  }
  let ids = []
  select.forEach(element => {
    ids.push(element.id)
  });
  let params = {
    ids: ids
  }
  let result = await interestPublishInterestPublishService(params);

  intertestList();

}
const handleSelectionChange = (val) => {
  select = val;
}

const interestTitle = ref('')

const showState = ref(0)
const changeResourceType = (val) => {
  showState.value = val;
}


const top = async (row) => {
  let params ={
    id:row.id
  }
  let result = await interestTopInterestPublishService(params);
  ElMessage.success('置顶成功');
  intertestList();

}

const cancelTop = async (row) => {
  let result = await interestCancelTopInterestPublishService(row.id);
  ElMessage.success('取消置顶成功');
  intertestList();

}


const setPopular = async (row) => {
  let result = await interestSetPopularService(row.id);
  ElMessage.success('置顶成功');
  intertestList();

}

const handleSortChange = async (row) => {
  likeOrder.value='';
  forwardOrder.value='';
  if(row.prop ==='likeCount'){
    likeOrder.value=row.order;
  }
  if(row.prop ==='forwardCount'){
    forwardOrder.value=row.order;
  }
  intertestList();
}


</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>好友管理</span>

      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="时间：">
        <el-date-picker
            v-model="day"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>


      <el-form-item label="账号：">
        <el-input  v-model="account" />
      </el-form-item>
      <el-form-item label="名称：">
        <el-input  v-model="name" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="intertestList">搜索</el-button>
        <el-button @click="day = '';plateId = '';account='';queryState='';name=''">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 文章列表 -->
    <el-table :data="interests" border style="width: 100%" @selection-change="handleSelectionChange" @sort-change="handleSortChange">

      <el-table-column label="序号" prop="id" width="100"></el-table-column>
      <el-table-column label="发布日期" prop="publishTime" width="200"></el-table-column>
      <el-table-column label="发布账号" prop="account" width="100"></el-table-column>
      <el-table-column label="账号名称" prop="name" width="100"></el-table-column>
      <el-table-column label="点赞数量" sortable="custom"   prop="likeCount" width="130"></el-table-column>
      <el-table-column label="是否为转发" width="200">
        <template v-slot="scope">
          <span v-if="scope.row.forwardId != 0">转发别人</span>
          <span v-else>自己发布</span>
        </template>
      </el-table-column>
      <el-table-column label="被转发数量" sortable="custom"  prop="forwardCount" width="130"></el-table-column>
      <el-table-column label="版块" prop="plateName" width="55"></el-table-column>
      <el-table-column label="内容类型" prop="resourceTypeValue" width="150"></el-table-column>
      <el-table-column label="标题" prop="title" :show-overflow-tooltip="true" width="100"></el-table-column>
      <el-table-column label="文字内容" prop="text" :show-overflow-tooltip="true" width="300"></el-table-column>
      <el-table-column label="文章内容" prop="article" :show-overflow-tooltip="true" width="300"></el-table-column>
      <el-table-column label="配图" width="200">
        <template v-slot="scope">
          <span v-for=" c in scope.row.images" >
             <img v-if="c.url" :src="c.url" width="40" height="40" class="head_pic" />
          </span>
        </template>
      </el-table-column>


      <el-table-column label="发布状态" width="100px">
        <template v-slot="scope">
          <span v-if="scope.row.publishState == 0">未发布</span>
          <span v-else>发布</span>
        </template>
      </el-table-column>




      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>


    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>


    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
      <!-- 添加文章表单 -->
      <el-form :model="interestModel" label-width="100px">
        <el-form-item label="版块">
          <el-select placeholder="请选择" v-model="interestModel.plateId">
            <el-option v-for="c in addPlates" :key="c.id" :label="c.name" :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容类型">
          <el-select placeholder="请选择" v-model="interestModel.resourceType"
                     :change="changeResourceType(interestModel.resourceType)">
            <el-option v-for="c in resourceTypes" :key="c.id" :label="c.resourceValue" :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布账号">
          <el-select placeholder="请选择" v-model="interestModel.userId">
            <el-option v-for="c in userInfos" :key="c.id" :label="c.name" :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" v-if="showState == 4">
          <el-input v-model="interestModel.title" type="text" style="width: 210px;"/>
        </el-form-item>


        <el-form-item label="配图" v-if="showState != 0">

          <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="/api/admin/upload/uploadFile"
              list-type="picture"
          >
            <el-button type="primary">上传图片</el-button>
            <template #tip>

            </template>
          </el-upload>
        </el-form-item>


        <el-form-item label="文字" v-if="showState == 0 || showState == 3">
          <el-input v-model="interestModel.text" type="textarea" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="文章" v-if="showState == 4">
          <div class="editor">

            <quill-editor theme="snow" v-model:content="interestModel.article" contentType="html">
            </quill-editor>

          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="title == '发布兴趣圈' ? addInterestPublish() : updateInterest()">保存</el-button>

        </el-form-item>
      </el-form>
    </el-drawer>


  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}


/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }



    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>